# -*- coding: utf-8 -*-
from flask_admin.contrib.sqla import ModelView
from flask_admin import expose, BaseView, AdminIndexView
from flask import redirect, request, render_template
from flask_login import logout_user
from flask_ckeditor import CKEditor, CKEditorField  # 导入扩展类 CKEditor 和 字段类
from blog_setting.myCrypto import Decrypt
from flask_admin.contrib.fileadmin import FileAdmin
from pyecharts import options as opts
from pyecharts.charts import Line, Pie, WordCloud
from .models import *
class Permission_IS:
    # 重写方法实现权限控制
    def is_accessible(self):
        user_name = Decrypt(request.cookies.get('uun'))
        password = Decrypt(request.cookies.get('uup'))
        user = db.session.query(BlogUser).filter(BlogUser.login_name == user_name, BlogUser.user_pwd == password,
                                                 BlogUser.locked == 0).first()  # 从用户数据中查找用户记录
        if user != None:
            return True
        return False
    # 访问页面没有权限时回调函数,可跳转登录
    def inaccessible_callback(self, name, **kwargs):
        # redirect to login page if user doesn't have access
        return redirect('/backstage/login/')

class FileBlogView(Permission_IS, FileAdmin):
    pass

class MicroBlogModelView(Permission_IS, ModelView):
    # can_delete = False  # disable model deletion
    page_size = 20  # the number of entries to display on the list view
    can_view_details = True
    column_display_pk = True

    # form_overrides = dict(content=CKEditorField)  # 重写表单字段，将 text 字段设为 CKEditorField
    create_template = '/backstage/edit.html'  # 指定创建记录的模板
    edit_template = '/backstage/edit.html'  # 指定编辑记录的模板

# pyecharts
def line_Admin():
    datadb = db.session.query(Visitor).filter(Visitor.visitor_id > 0).all()
    data = []
    datanum = []
    for i in datadb:
        data.append(i.create_time)
    for k, v in enumerate(data):
        datanum.append(k+1)
    chart = Line(init_opts=opts.InitOpts(width='100%', height='25rem'))
    chart.add_xaxis(data)
    chart.add_yaxis('', datanum, is_smooth=False,
                    symbol="emptyCircle",
                    is_symbol_show=True,
                    label_opts=opts.LabelOpts(is_show=False),
                    areastyle_opts=opts.AreaStyleOpts(opacity=1, color="#C67570"), )
    chart.set_global_opts(
        title_opts=opts.TitleOpts(title="游客访问量", subtitle="此折线图由游客访问的时间段当时的游客总量生成"),
        datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")],
    )
    return chart.render_embed()

def pie_Admin():
    datadb = db.session.query(Visitor).filter(Visitor.visitor_id > 0).all()
    data = []
    for i in datadb:
        data.append(i.os_type)
    dataset = list(set(data))
    datacount = []
    for i in dataset:
        datacount.append(data.count(i))
    pie = Pie(init_opts=opts.InitOpts(width='100%', height='25rem'))
    pie.add("", [(dataset[i], datacount[i]) for i in range(len(dataset))])
    pie.set_global_opts(title_opts=opts.TitleOpts(title="设备类型分布图", subtitle="此分类图由所有游客设备类型生成"))
    return pie.render_embed()

# admin序列化
class Home_Admin(Permission_IS, AdminIndexView):
    @expose('/')
    def index(self):
        from .views import Visitor_Add
        Visitor_Add()
        charts = {
                'line': line_Admin(),
                'pie': pie_Admin(),
                }

        return self.render('/backstage/index.html', charts =charts)




class Logout_Admin(Permission_IS, BaseView):
    @expose('/')
    def index(self):
        logout_user()  # 登出用户
        rep = redirect('/backstage/login/')  # 重定向回首页
        rep.set_cookie('uup', '')
        return rep

class BlogUser_Admin(MicroBlogModelView):
    column_searchable_list = ('user_id', 'login_name')
    column_filters = ('locked', 'role', 'is_deleted')
    column_labels = {
        'user_id': u'ID',
        'login_name': u'用户名',
        'user_pwd': u'密码',
        'locked': u'锁定0-1冻结-2黑名单',
        'role': u'角色',
        'is_deleted': u'状态0-1注销',
        'create_time': u'创建时间',
        'draft_articles': u'关联-草稿',
    }
    column_list = ('user_id', 'login_name', 'user_pwd', 'locked', 'role', 'is_deleted', 'create_time')
    def __init__(self, session, **kwargs):
        super(BlogUser_Admin, self).__init__(BlogUser, session, **kwargs)
class DraftArticle_Admin(MicroBlogModelView):
    column_searchable_list = ('draft_id', 'title')
    column_filters = ('user_id', 'tag',)
    column_labels = {
        'draft_id': u'ID',
        'user_id': u'外键-用户表',
        'title': u'标题',
        'content': u'内容',
        'intro': u'简介',
        'cover_img': u'封面图url',
        'tag': u'标签',
        'create_time': u'创建时间',
        'update_time': u'更新时间',
        'user': u'外键-用户表',
    }
    column_list = ('draft_id', 'user_id', 'title', 'intro', 'cover_img', 'tag', 'create_time', 'update_time')
    def __init__(self, session, **kwargs):
        super(DraftArticle_Admin, self).__init__(DraftArticle, session, **kwargs)
class MultiArticle_Admin(MicroBlogModelView):
    column_searchable_list = ('article_id', 'title')
    column_filters = ('class_sub_id', 'tag',)
    column_labels = {
        'article_id': u'ID',
        'class_sub_id': u'外键-文章分类表',
        'title': u'标题',
        'content': u'内容',
        'intro': u'简介',
        'cover_img': u'封面图url',
        'tag': u'标签',
        'create_time': u'创建时间',
        'update_time': u'更新时间',
        'class_sub': u'外键-文章类',
        'praise_articles': u'关联-文章赞',
    }
    column_list = ('article_id', 'class_sub_id', 'title', 'intro', 'cover_img', 'tag', 'create_time', 'update_time')
    def __init__(self, session, **kwargs):
        super(MultiArticle_Admin, self).__init__(MultiArticle, session, **kwargs)

class MultiClassSub_Admin(MicroBlogModelView):
    column_searchable_list = ('class_sub_id', 'class_sub_name')
    column_labels = {
        'class_sub_id': u'ID',
        'class_sub_name': u'分类名',
        'intro': u'简介',
        'create_time': u'创建时间',
        'multi_articles': u'关联-文章页',
    }
    column_list = ('class_sub_id', 'class_sub_name', 'intro', 'create_time')
    def __init__(self, session, **kwargs):
        super(MultiClassSub_Admin, self).__init__(MultiClassSub, session, **kwargs)
class PraiseArticle_Admin(MicroBlogModelView):
    column_searchable_list = ('praise_id', )
    column_filters = ('article_id', 'visitor_id', 'is_praise')
    column_labels = {
        'praise_id': u'ID',
        'article_id': u'外键-文章页ID',
        'visitor_id': u'外键-游客ID',
        'is_praise': u'0没点, 1点了',
        'article': u'外键-文章页',
        'visitor': u'外键-游客表',
    }
    column_list = ('praise_id', 'article_id', 'visitor_id', 'is_praise',)
    def __init__(self, session, **kwargs):
        super(PraiseArticle_Admin, self).__init__(PraiseArticle, session, **kwargs)

class PraiseTool_Admin(MicroBlogModelView):
    column_searchable_list = ('praise_id', )
    column_filters = ('tool_page_id', 'visitor_id', 'is_praise')
    column_labels = {
        'praise_id': u'ID',
        'tool_page_id': u'外键-工具页ID',
        'visitor_id': u'外键-游客ID',
        'is_praise': u'0没点, 1点了',
        'tool_page': u'外键-工具页',
        'visitor': u'外键-游客表',
    }
    column_list = ('praise_id', 'tool_page_id', 'visitor_id', 'is_praise',)
    def __init__(self, session, **kwargs):
        super(PraiseTool_Admin, self).__init__(PraiseTool, session, **kwargs)

class Speak_Admin(MicroBlogModelView):
    column_searchable_list = ('speak_id', 'nick', 'contact' )
    column_labels = {
        'speak_id': u'ID',
        'nick': u'昵称(匿名',
        'contact': u'联系方式(默认0邮箱，1手机号',
        'content': u'详细说明内容',
        'simple_conten': u'简单说明',
        'create_time': u'创建时间',
        'visitor': u'外键-游客表',
    }
    column_list = ('speak_id', 'nick', 'contact', 'content', 'simple_conten', 'create_time')
    def __init__(self, session, **kwargs):
        super(Speak_Admin, self).__init__(Speak, session, **kwargs)

class Sponsor_Admin(MicroBlogModelView):
    column_searchable_list = ('sponsor_id', 'nick', 'contact' )
    column_filters = ('is_show', 'gold_num', )
    column_labels = {
        'sponsor_id': u'ID',
        'image_head': u'头像url',
        'nick': u'昵称(匿名',
        'contact': u'联系方式',
        'url_link': u'链接网址',
        'is_show': u'1显示 or 0不显示',
        'gold_num': u'金额',
        'create_time': u'创建时间',
        # 'praise_tools': u'关联-工具赞',
    }
    column_list = ('sponsor_id', 'image_head', 'nick', 'contact', 'url_link', 'is_show', 'gold_num', 'create_time')
    def __init__(self, session, **kwargs):
        super(Sponsor_Admin, self).__init__(Sponsor, session, **kwargs)

class ToolsNet_Admin(MicroBlogModelView):
    column_searchable_list = ('tools_id', 'tools_name',  )
    column_labels = {
        'tools_id': u'ID',
        'tools_name': u'工具类名',
        'intro': u'简介',
        'create_time': u'创建时间',
        'tools_net_pages': u'关联-工具页',
    }
    column_list = ('tools_id', 'tools_name', 'intro', 'create_time')
    def __init__(self, session, **kwargs):
        super(ToolsNet_Admin, self).__init__(ToolsNet, session, **kwargs)

class ToolsNetPage_Admin(MicroBlogModelView):
    column_searchable_list = ('tool_page_id', 'title',  )
    column_filters = ('tools', 'tag', )
    column_labels = {
        'tool_page_id':u'ID',
        'tools': u'外键-工具类',
        'title': u'标题',
        'content': u'内容',
        'intro': u'简介',
        'tag': u'标签',
        'create_time': u'创建时间',
        'praise_tools': u'关联-工具赞',
    }
    column_list = ('tool_page_id','tools', 'title', 'intro', 'tag', 'create_time' )
    def __init__(self, session, **kwargs):
        super(ToolsNetPage_Admin, self).__init__(ToolsNetPage, session, **kwargs)

class Visitor_Admin(MicroBlogModelView):
    column_searchable_list = ('visitor_id', 'visitor_id_address',  )
    column_filters = ('os_type', 'region', )
    column_labels = {
        'visitor_id':u'ID',
        'visitor_id_address': u'游客本机ID地址',
        'os_type': u'设备系统类型',
        'region': u'所在的地区',
        'create_time': u'创建时间',
        'praise_articles': u'关联-文章赞',
        'praise_tools': u'关联-工具赞',
        'speaks': u'关联-留言表',
    }
    column_list = ('visitor_id','visitor_id_address', 'os_type', 'region', 'create_time' )
    def __init__(self, session, **kwargs):
        super(Visitor_Admin, self).__init__(Visitor, session, **kwargs)